package com.example.chongwushangcheng.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.chongwushangcheng.adapter.BidderAdapter;
import com.example.chongwushangcheng.adapter.CarouselAdapter;
import com.example.chongwushangcheng.adapter.SimilarProductAdapter;
import com.example.chongwushangcheng.model.AuctionProductDetail;
import com.example.chongwushangcheng.model.Bidder;
import com.example.chongwushangcheng.ui.TransactionRulesActivity;
import com.example.petshopping.R;
import com.example.petshopping.model.Product;
import com.example.petshopping.model.AppPetAuctionItemRespVO;
import com.example.petshopping.model.AppProductSpuDetailRespVO;
import com.example.petshopping.model.CommonResult;
import com.example.petshopping.model.PageResult;
import com.example.petshopping.model.AppPetAuctionBidRespVO;
import com.example.petshopping.network.RetrofitClient;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 拍卖商品详情页面
 */
public class AquariumDetailActivity extends AppCompatActivity {

    // UI组件
    private ImageView ivBack;
    private ImageView ivUserAvatar;
    private TextView tvUserName;
    private Button btnFollow;
    private EditText etSearch;
    private ViewPager2 viewPagerCarousel;
    private LinearLayout indicatorContainer;
    private LinearLayout serviceGuarantee;
    private TextView tvProductTitle;
    private TextView tvProductDescription;
    private TextView tvCurrentPrice;
    private TextView tvCountdown;
    private TextView tvOldPrice;
    private ImageView ivRefresh;
    private Button btnBid;
    private RecyclerView rvBidders;
    private RecyclerView rvSimilarProducts;
    private TextView tvTransactionRules;
    private TextView tvPriceRateValue;
    private TextView price_increment;

    // 适配器
    private CarouselAdapter carouselAdapter;
    private BidderAdapter bidderAdapter;
    private SimilarProductAdapter similarProductAdapter;

    // 数据
    private AuctionProductDetail currentProduct;
    private List<Integer> carouselImages;
    private List<Bidder> bidderList;
    private List<Product> similarProducts;

    // 定时器相关
    private Handler countdownHandler;
    private Runnable countdownRunnable;
    private long auctionEndEpochMillis = -1L;

    // 轮播图定时器
    private Handler carouselHandler;
    private Runnable carouselRunnable;
    private int currentCarouselIndex = 0;

    // 当前选中的出价
    private int selectedBidPrice = 440;
    // 当前展示的拍卖商品 ID（用于刷新价格）
    private Long currentItemId = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aquarium_detail);

        // 获取传递过来的商品信息
        String id = getIntent().getStringExtra("id");
        String spuId = getIntent().getStringExtra("spuId");
        String name = getIntent().getStringExtra("name");
        String price = getIntent().getStringExtra("price");
        String sellerId = getIntent().getStringExtra("sellerId");
        String sellerName = getIntent().getStringExtra("sellerName");
        String sellerAvatar = getIntent().getStringExtra("sellerAvatar");
        String auctionEndTime = getIntent().getStringExtra("auctionEndTime");
        // 创建商品对象
        initViews();
        // 初始化数据
        initData();
        // 初始化轮播图
        initCarousel();
        // 初始化RecyclerView
        initRecyclerViews();
        // 初始化点击监听器
        initClickListeners();
        // 启动倒计时
        startCountdown();
        // 启动轮播图自动滚动
        startCarouselAutoScroll();
        // 页面加载时，基于传入的 id 重新从服务端拉取并初始化拍卖商品数据
        initProductDataFromServer(id, name);
        // 页面加载时，基于传入的 spuId 拉取并初始化 SPU 商品详情
        initSpuDetailFromServer(spuId);

        // 页面加载时，基于传入的 id 拉取并初始化拍卖出价记录
        initBidRecordsFromServer(id);

        // 保存当前 itemId 以便刷新时使用
        try {
            if (id != null && !id.trim().isEmpty()) {
                currentItemId = Long.parseLong(id);
            }
        } catch (NumberFormatException ignored) {
        }

    }

    private void initViews() {
        ivBack = findViewById(R.id.ivBack);
        ivUserAvatar = findViewById(R.id.ivUserAvatar);
        tvUserName = findViewById(R.id.tvUserName);
        btnFollow = findViewById(R.id.btnFollow);
        etSearch = findViewById(R.id.etSearch);
        viewPagerCarousel = findViewById(R.id.viewPagerCarousel);
        indicatorContainer = findViewById(R.id.indicatorContainer);
        serviceGuarantee = findViewById(R.id.serviceGuarantee);
        tvProductTitle = findViewById(R.id.tvProductTitle);
        tvProductDescription = findViewById(R.id.tvProductDescription);
        tvCurrentPrice = findViewById(R.id.tvCurrentPrice);
        tvCountdown = findViewById(R.id.tvCountdown);
        tvOldPrice = findViewById(R.id.tvOldPrice);
        ivRefresh = findViewById(R.id.ivRefresh);
        btnBid = findViewById(R.id.btnBid);
        rvBidders = findViewById(R.id.rvBidders);
        rvSimilarProducts = findViewById(R.id.rvSimilarProducts);
        tvTransactionRules = findViewById(R.id.tvTransactionRules);
        tvPriceRateValue = findViewById(R.id.tvPriceRateValue);
        price_increment = findViewById(R.id.price_increment);

        // 设置删除线效果
        if (tvOldPrice != null) {
            tvOldPrice.setPaintFlags(tvOldPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        }
    }

    private void initData() {
        // 初始化轮播图数据
        carouselImages = Arrays.asList(
                R.drawable.yugang, R.drawable.aquarium_tank, R.drawable.yugang, R.drawable.yugang, R.drawable.yugang
        );

        // 初始化商品数据
//        currentProduct = new AuctionProductDetail();
//        currentProduct.setTitle("超白玻璃生态鱼缸 水族箱中型客厅创意造景金鱼缸");
//        currentProduct.setDescription("高透玻璃，360度无死角，简约时尚设计，配套过滤系统，适合热带鱼、金鱼、水草造景。");
//        currentProduct.setCurrentPrice(432);
//        currentProduct.setSellerName("招财猫旺财狗");
//        currentProduct.setFollowed(false);

        // 初始化出价者数据（从服务端获取，这里只初始化空列表）
        bidderList = new ArrayList<>();

        // 初始化同类商品数据
        similarProducts = new ArrayList<>();
        similarProducts.add(new Product("1", "宠物标题宠物标题宠物标题宠物标题", "432", "招财猫旺财狗"));
        similarProducts.add(new Product("2", "超白玻璃生态鱼缸 水族箱中型客厅创意造景金鱼缸", "432", "招财猫旺财狗"));
        similarProducts.add(new Product("3", "宠物标题宠物标题宠物标题宠物标题", "432", "招财猫旺财狗"));
        similarProducts.add(new Product("4", "超白玻璃生DVD是多少出点啥事大萨达超大是超大是超大态鱼缸 水族箱中型客厅创意造景金鱼缸", "432", "招财猫旺财狗"));
    }

    // 通过接口请求获取SPU详情并刷新页面（GET /product/spu/get-detail?id=xxx）
    private void initSpuDetailFromServer(String spuId) {
        if (spuId == null || spuId.trim().isEmpty()) {
            return;
        }
        try {
            Long idLong = Long.parseLong(spuId);
            Call<CommonResult<AppProductSpuDetailRespVO>> call =
                    RetrofitClient.getInstance().getApiService().getProductSpuDetail(idLong);

            call.enqueue(new Callback<CommonResult<AppProductSpuDetailRespVO>>() {
                @Override
                public void onResponse(Call<CommonResult<AppProductSpuDetailRespVO>> call,
                                       Response<CommonResult<AppProductSpuDetailRespVO>> response) {
                    if (!response.isSuccessful() || response.body() == null) {
                        return;
                    }
                    CommonResult<AppProductSpuDetailRespVO> result = response.body();
                    if (result.isSuccess() && result.getData() != null) {
                        applySpuDetail(result.getData());
                    }
                }

                @Override
                public void onFailure(Call<CommonResult<AppProductSpuDetailRespVO>> call, Throwable t) {
                    // 静默失败即可
                }
            });
        } catch (NumberFormatException ignored) {
        }
    }

    // 应用SPU详情
    @SuppressLint("SetTextI18n")
    private void applySpuDetail(AppProductSpuDetailRespVO data) {
        if (data == null) return;

        if (currentProduct == null) {
            currentProduct = new AuctionProductDetail();
        }
        if (tvProductDescription != null) {
            String desc = data.getIntroduction() != null ? data.getIntroduction() : data.getDescription();
            if (desc != null) tvProductDescription.setText(desc);
        }
        // 图片轮播：如果服务端返回轮播图，使用网络图刷新
        if (data.getSliderPicUrls() != null && !data.getSliderPicUrls().isEmpty()) {
            currentProduct.setImageUrls(data.getSliderPicUrls());
            // 切换为使用网络图片的构造函数
            carouselAdapter = new CarouselAdapter(this, data.getSliderPicUrls());
            viewPagerCarousel.setAdapter(carouselAdapter);
            createIndicators();
        }
    }

    // 通过接口请求获取拍卖出价记录并初始化页面
    private void initBidRecordsFromServer(String itemId) {
        if (itemId == null || itemId.trim().isEmpty()) {
            return;
        }

        try {
            Long idLong = Long.parseLong(itemId);
            Call<CommonResult<PageResult<AppPetAuctionBidRespVO>>> call =
                    RetrofitClient.getInstance().getApiService().getPetAuctionBidPage(
                            1, // 第一页
                            3, // 每页3条数据
                            idLong, // 拍卖商品ID
                            null, // 出价用户ID（不限制）
                            null, // 出价用户昵称（不限制）
                            null, // 出价金额（不限制）
                            null  // 状态（不限制）
                    );

            call.enqueue(new Callback<CommonResult<PageResult<AppPetAuctionBidRespVO>>>() {
                @Override
                public void onResponse(Call<CommonResult<PageResult<AppPetAuctionBidRespVO>>> call,
                                       Response<CommonResult<PageResult<AppPetAuctionBidRespVO>>> response) {
                    if (!response.isSuccessful() || response.body() == null) {
                        return;
                    }

                    CommonResult<PageResult<AppPetAuctionBidRespVO>> result = response.body();
                    if (result.isSuccess() && result.getData() != null) {
                        PageResult<AppPetAuctionBidRespVO> pageResult = result.getData();
                        if (pageResult.getList() != null && !pageResult.getList().isEmpty()) {
                            // 更新出价记录列表
                            bidderAdapter.updateBiddersFromServer(pageResult.getList());
                        }
                    }
                }

                @Override
                public void onFailure(Call<CommonResult<PageResult<AppPetAuctionBidRespVO>>> call, Throwable t) {
                    // 静默失败，不影响页面显示
                }
            });

        } catch (NumberFormatException ignored) {
        }
    }

    // 格式化价格
    private String formatPriceFromCents(Integer cents) {
        try {
            java.math.BigDecimal fen = new java.math.BigDecimal(cents);
            java.math.BigDecimal yuan = fen.divide(new java.math.BigDecimal(100), 2, java.math.RoundingMode.HALF_UP);
            return yuan.stripTrailingZeros().toPlainString();
        } catch (Exception e) {
            return String.valueOf(cents);
        }
    }

    // 通过接口请求获取商品详情并初始化页面
    private void initProductDataFromServer(String itemId, String name) {
        if (itemId == null || itemId.trim().isEmpty()) {
            Toast.makeText(this, "缺少商品ID，无法加载详情", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            Long idLong = Long.parseLong(itemId);
            Call<CommonResult<AppPetAuctionItemRespVO>> call =
                    RetrofitClient.getInstance().getApiService().getPetAuctionItem(idLong);

            call.enqueue(new Callback<CommonResult<AppPetAuctionItemRespVO>>() {
                @Override
                public void onResponse(Call<CommonResult<AppPetAuctionItemRespVO>> call,
                                       Response<CommonResult<AppPetAuctionItemRespVO>> response) {
                    if (!response.isSuccessful() || response.body() == null) {
                        Toast.makeText(AquariumDetailActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    CommonResult<AppPetAuctionItemRespVO> result = response.body();
                    if (result.isSuccess() && result.getData() != null) {
                        applyProductData(result.getData(), name);
                    } else {
                        Toast.makeText(AquariumDetailActivity.this,
                                result.getMsg() != null ? result.getMsg() : "加载失败",
                                Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<CommonResult<AppPetAuctionItemRespVO>> call, Throwable t) {
                    Toast.makeText(AquariumDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

        } catch (NumberFormatException e) {
            Toast.makeText(this, "商品ID格式错误", Toast.LENGTH_SHORT).show();
        }
    }

    // 将服务端数据映射到本地对象并刷新UI
    @SuppressLint("SetTextI18n")
    private void applyProductData(AppPetAuctionItemRespVO data, String name) {
        if (data == null) return;

        // 更新当前商品对象
        if (currentProduct == null) {
            currentProduct = new AuctionProductDetail();
        }
        currentProduct.setTitle(data.getName());
        currentProduct.setCurrentPrice(data.getCurrentPrice());
        currentProduct.setSellerName(data.getSellerName());
        currentProduct.setSellerAvatar(data.getSellerAvatar());
        if (data.getEndTime() != null) {
            currentProduct.setEndTime(data.getEndTime().toString()); // 倒计时
        } else {
            currentProduct.setEndTime("倒计时异常");
        }


        // 刷新UI
        if (tvProductTitle != null) {
            tvProductTitle.setText(name);
        }
        if (tvCurrentPrice != null && data.getCurrentPrice() != null) {
            tvCurrentPrice.setText(String.valueOf(data.getCurrentPrice()));
        }
        if (tvUserName != null)
            tvUserName.setText(data.getSellerName() != null ? data.getSellerName() : "");
        if (ivUserAvatar != null && data.getSellerAvatar() != null) {
            Glide.with(this).load(data.getSellerAvatar()).into(ivUserAvatar);
        }
        if (tvOldPrice != null && data.getStartingPrice() != null) {
            tvOldPrice.setText(String.valueOf(data.getStartingPrice()));
        }
        if (price_increment != null) {
            price_increment.setText("¥ " + String.valueOf(data.getPriceIncrement()));
        }
        BigDecimal sellerFee = data.getSellerFeeRate();
        BigDecimal buyerFee = data.getBuyerFeeRate();
        if (tvPriceRateValue != null) {
            if (sellerFee != null && buyerFee != null) {
                String sellerFeeRate = sellerFee.multiply(new BigDecimal("100")).toString().substring(0, 1);
                String buyerFeeRate = buyerFee.multiply(new BigDecimal("100")).toString().substring(0, 1);
                tvPriceRateValue.setText(String.format("卖家%s%%，买家%s%%", sellerFeeRate, buyerFeeRate));
            } else {
                tvPriceRateValue.setText("费率显示异常");
            }
        }
        // 基于服务端 endTime 启动/刷新倒计时（兼容 API 21，不使用 java.time.ZoneId）
        if (data.getEndTime() != null) {
            String endTimeStr = data.getEndTime().toString();
            auctionEndEpochMillis = parseEndTimeToMillis(endTimeStr);

            // 重置并刷新倒计时显示
            if (countdownHandler != null && countdownRunnable != null) {
                countdownHandler.removeCallbacks(countdownRunnable);
            }
            updateCountdownDisplay();
            startCountdown();
        } else {
            if (tvCountdown != null) tvCountdown.setText("");
        }
        // 其他展示信息（如倒计时、描述、图片等）可根据需要继续补充
    }

    private void initCarousel() {
        carouselAdapter = new CarouselAdapter(this, carouselImages, true);
        viewPagerCarousel.setAdapter(carouselAdapter);

        // 创建指示器
        createIndicators();

        // 监听页面切换
        viewPagerCarousel.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                currentCarouselIndex = position;
                updateIndicators(position);
            }
        });
    }

    private void createIndicators() {
        indicatorContainer.removeAllViews();
        for (int i = 0; i < carouselImages.size(); i++) {
            View indicator = new View(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(24, 24);
            params.setMargins(8, 0, 8, 0);
            indicator.setLayoutParams(params);

            if (i == 0) {
                indicator.setBackgroundResource(R.drawable.indicator_active);
            } else {
                indicator.setBackgroundResource(R.drawable.indicator_inactive);
            }

            indicatorContainer.addView(indicator);
        }
    }

    private void updateIndicators(int position) {
        for (int i = 0; i < indicatorContainer.getChildCount(); i++) {
            View indicator = indicatorContainer.getChildAt(i);
            if (i == position) {
                indicator.setBackgroundResource(R.drawable.indicator_active);
            } else {
                indicator.setBackgroundResource(R.drawable.indicator_inactive);
            }
        }
    }

    private void initRecyclerViews() {
        // 初始化出价者列表
        bidderAdapter = new BidderAdapter(this, bidderList);
        rvBidders.setLayoutManager(new LinearLayoutManager(this));
        rvBidders.setAdapter(bidderAdapter);

        // 初始化同类商品列表（2列网格）
        similarProductAdapter = new SimilarProductAdapter(this, similarProducts);
        rvSimilarProducts.setLayoutManager(new GridLayoutManager(this, 2));
        rvSimilarProducts.setAdapter(similarProductAdapter);

        // 设置同类商品点击事件
        similarProductAdapter.setOnProductClickListener(new SimilarProductAdapter.OnProductClickListener() {
            @Override
            public void onProductClick(Product product) {
                Toast.makeText(AquariumDetailActivity.this, "点击商品: " + product.getName(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onHeartClick(Product product, int position) {
                Toast.makeText(AquariumDetailActivity.this, "收藏: " + product.getName(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDeleteClick(Product product, int position) {
                similarProductAdapter.removeItem(position);
                Toast.makeText(AquariumDetailActivity.this, "删除: " + product.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initClickListeners() {
        // 返回按钮 — 在返回时通知调用页面刷新
        ivBack.setOnClickListener(v -> {
            setResult(RESULT_OK);
            finish();
        });

        // 关注按钮
        btnFollow.setOnClickListener(v -> {
            if (currentProduct.isFollowed()) {
                btnFollow.setText("关注");
                btnFollow.setBackgroundResource(R.drawable.bg_follow_button);
                currentProduct.setFollowed(false);
            } else {
                btnFollow.setText("已关注");
                btnFollow.setBackgroundColor(getResources().getColor(R.color.text_gray));
                currentProduct.setFollowed(true);
            }
        });

        // 刷新价格按钮
        ivRefresh.setOnClickListener(v -> {
            // 添加旋转动画效果
            v.animate().rotation(v.getRotation() + 360).setDuration(500).start();

            // 发起网络请求，调用后端接口获取最新的拍卖商品信息（只取 currentPrice 字段）
            if (currentItemId == null) {
                Toast.makeText(AquariumDetailActivity.this, "未指定商品ID，无法刷新", Toast.LENGTH_SHORT).show();
                return;
            }

            Call<CommonResult<AppPetAuctionItemRespVO>> call =
                    RetrofitClient.getInstance().getApiService().getPetAuctionItem(currentItemId);

            call.enqueue(new Callback<CommonResult<AppPetAuctionItemRespVO>>() {
                @Override
                public void onResponse(Call<CommonResult<AppPetAuctionItemRespVO>> call,
                                       Response<CommonResult<AppPetAuctionItemRespVO>> response) {
                    if (!response.isSuccessful() || response.body() == null) {
                        Toast.makeText(AquariumDetailActivity.this, "刷新失败：响应异常", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    CommonResult<AppPetAuctionItemRespVO> result = response.body();
                    if (result.isSuccess() && result.getData() != null) {
                        AppPetAuctionItemRespVO data = result.getData();
                        Integer latestPrice = data.getCurrentPrice();
                        if (latestPrice != null) {
                            // 更新 UI 显示（主线程）
                            tvCurrentPrice.setText(String.valueOf(latestPrice));
                            Toast.makeText(AquariumDetailActivity.this, "价格已刷新", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(AquariumDetailActivity.this, "刷新失败：未包含价格信息", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(AquariumDetailActivity.this,
                                result.getMsg() != null ? result.getMsg() : "刷新失败",
                                Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<CommonResult<AppPetAuctionItemRespVO>> call, Throwable t) {
                    Toast.makeText(AquariumDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        });

        // 服务保障点击
        serviceGuarantee.setOnClickListener(v -> showServiceDialog());

        // 出价按钮
        btnBid.setOnClickListener(v -> showBidDialog());

        // 交易规则与服务协议点击
        tvTransactionRules.setOnClickListener(v -> {
            Intent intent = new Intent(AquariumDetailActivity.this, TransactionRulesActivity.class);
            overridePendingTransition(0, 0);
            startActivity(intent);
        });
    }

    private void startCountdown() {
        if (auctionEndEpochMillis <= 0) {
            return; // 未设置结束时间，不启动
        }
        if (countdownHandler == null) {
            countdownHandler = new Handler();
        }
        if (countdownRunnable != null) {
            countdownHandler.removeCallbacks(countdownRunnable);
        }
        countdownRunnable = new Runnable() {
            @Override
            public void run() {
                long diff = auctionEndEpochMillis - System.currentTimeMillis();
                if (diff <= 0) {
                    if (tvCountdown != null) tvCountdown.setText("已截拍");
                    return;
                }
                updateCountdownDisplay();
                countdownHandler.postDelayed(this, 1000);
            }
        };
        countdownHandler.post(countdownRunnable);
    }

    private void updateCountdownDisplay() {
        if (tvCountdown == null) return;
        long diff = auctionEndEpochMillis - System.currentTimeMillis();
        if (diff <= 0) {
            tvCountdown.setText("已截拍");
            return;
        }
        long totalSeconds = diff / 1000;
        long days = totalSeconds / (24 * 3600);
        long hours = (totalSeconds % (24 * 3600)) / 3600;
        long minutes = (totalSeconds % 3600) / 60;
        long seconds = totalSeconds % 60;
        String countdownText = String.format(Locale.getDefault(), "还剩%d天%d小时%d分%d秒", days, hours, minutes, seconds);
        tvCountdown.setText(countdownText);
    }

    // 解析多种可能的 endTime 字符串格式为毫秒时间戳（支持 API 21+）
    private long parseEndTimeToMillis(String endTimeStr) {
        if (endTimeStr == null || endTimeStr.trim().isEmpty()) return -1L;
        // 先尝试直接作为毫秒时间戳/秒时间戳
        try {
            long asLong = Long.parseLong(endTimeStr.trim());
            // 粗略判断位数：>= 1e12 认为是毫秒；否则按秒
            if (asLong > 1000_000_000_000L) return asLong;
            if (asLong > 0) return asLong * 1000L;
        } catch (NumberFormatException ignored) {
        }
        // 常见格式示例：
        // 1) 2025-07-05T23:59:59 (ISO-8601 无毫秒)
        // 2) 2025-07-05T23:59:59.123 (ISO-8601 有毫秒)
        // 3) 2025-07-05 23:59:59 (空格分隔)
        // 4) 2025/07/05 23:59:59
        // 服务端若包含时区信息(+08:00/Z)且 toString() 被简化，可能无法直接解析，此处做基本兜底。

        String normalized = endTimeStr.replace('T', ' ');
        String[] patterns = new String[]{
                "yyyy-MM-dd HH:mm:ss.SSS",
                "yyyy-MM-dd HH:mm:ss",
                "yyyy/MM/dd HH:mm:ss.SSS",
                "yyyy/MM/dd HH:mm:ss"
        };
        for (String pattern : patterns) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.getDefault());
                sdf.setLenient(false);
                Date date = sdf.parse(normalized);
                if (date != null) return date.getTime();
            } catch (ParseException ignored) {
            }
        }
        // 如果仍旧无法解析，尝试仅日期部分
        String[] dateOnlyPatterns = new String[]{
                "yyyy-MM-dd",
                "yyyy/MM/dd"
        };
        for (String pattern : dateOnlyPatterns) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.getDefault());
                sdf.setLenient(false);
                Date date = sdf.parse(normalized);
                if (date != null) return date.getTime();
            } catch (ParseException ignored) {
            }
        }
        return -1L;
    }

    private void startCarouselAutoScroll() {
        carouselHandler = new Handler();
        carouselRunnable = new Runnable() {
            @Override
            public void run() {
                if (carouselImages.size() > 1) {
                    currentCarouselIndex = (currentCarouselIndex + 1) % carouselImages.size();
                    viewPagerCarousel.setCurrentItem(currentCarouselIndex, true);
                }
                carouselHandler.postDelayed(this, 3000); // 3秒切换一次
            }
        };
        carouselHandler.postDelayed(carouselRunnable, 3000);
    }

    private void showServiceDialog() {
        BottomSheetDialog dialog = new BottomSheetDialog(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_service_guarantee, null);

        // 强制设置布局参数为全屏宽度
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        dialogView.setLayoutParams(layoutParams);

        dialog.setContentView(dialogView);

        // 关闭按钮
        ImageView ivClose = dialogView.findViewById(R.id.ivCloseDialog);
        if (ivClose != null) {
            ivClose.setOnClickListener(v -> dialog.dismiss());
        }

        // 了解详情点击事件
        TextView tvDetailLink = dialogView.findViewById(R.id.tv_detail_link);
        if (tvDetailLink != null) {
            tvDetailLink.setOnClickListener(v -> {
                // 关闭当前dialog
                dialog.dismiss();
                // 跳转到无理由退货退款页面，禁用默认动画
                Intent intent = new Intent(AquariumDetailActivity.this, NoReasonRefundActivity.class);
                startActivity(intent);
                // 禁用默认跳转动画
                overridePendingTransition(0, 0);
            });
        }

        // 确保弹窗全屏宽度并显示圆角
        dialog.setOnShowListener(dialogInterface -> {
            BottomSheetDialog bottomSheetDialog = (BottomSheetDialog) dialogInterface;
            Window window = bottomSheetDialog.getWindow();
            if (window != null) {
                // 获取屏幕宽度
                android.util.DisplayMetrics metrics = new android.util.DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);
                int screenWidth = metrics.widthPixels;

                // 设置窗口背景为透明，让内容视图的背景显示出来
                window.setBackgroundDrawableResource(android.R.color.transparent);

                // 设置窗口属性
                WindowManager.LayoutParams params = window.getAttributes();
                params.width = screenWidth;
                params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                params.horizontalMargin = 0;
                params.verticalMargin = 0;
                window.setAttributes(params);

                // 移除所有padding和margin
                window.getDecorView().setPadding(0, 0, 0, 0);
                window.setLayout(screenWidth, ViewGroup.LayoutParams.WRAP_CONTENT);

                // 强制设置对话框视图的布局参数
                ViewGroup.LayoutParams dialogParams = dialogView.getLayoutParams();
                if (dialogParams != null) {
                    dialogParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    dialogView.setLayoutParams(dialogParams);
                }

                // 移除对话框视图的padding和margin
                dialogView.setPadding(0, 0, 0, 0);
                if (dialogView instanceof ViewGroup) {
                    ViewGroup viewGroup = (ViewGroup) dialogView;
                    ViewGroup.MarginLayoutParams marginParams =
                            (ViewGroup.MarginLayoutParams) viewGroup.getLayoutParams();
                    if (marginParams != null) {
                        marginParams.setMargins(0, 0, 0, 0);
                        viewGroup.setLayoutParams(marginParams);
                    }
                }

                // 确保背景圆角显示
                dialogView.setClipToOutline(true);

                // 查找并设置 BottomSheet 的背景
                View bottomSheet = bottomSheetDialog.findViewById(com.google.android.material.R.id.design_bottom_sheet);
                if (bottomSheet != null) {
                    bottomSheet.setBackgroundResource(android.R.color.transparent);
                }

                // 强制设置内容视图的背景
                dialogView.setBackgroundResource(R.drawable.bg_dialog);
            }
        });

        dialog.show();
    }

    private void showBidDialog() {
        BottomSheetDialog dialog = new BottomSheetDialog(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_bid, null);

        // 强制设置布局参数为全屏宽度
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        dialogView.setLayoutParams(layoutParams);

        dialog.setContentView(dialogView);

        // 关闭按钮
        ImageView ivClose = dialogView.findViewById(R.id.ivCloseBidDialog);
        if (ivClose != null) {
            ivClose.setOnClickListener(v -> dialog.dismiss());
        }

        // 价格选择容器
        LinearLayout llPrice440 = dialogView.findViewById(R.id.llPrice440);
        LinearLayout llPrice448 = dialogView.findViewById(R.id.llPrice448);
        LinearLayout llPriceOther = dialogView.findViewById(R.id.llPriceOther);

        // 动态显示文本视图
        TextView tvDialogCurrentPrice = dialogView.findViewById(R.id.tvDialogCurrentPrice);
        TextView tvDialogPriceIncrement = dialogView.findViewById(R.id.tvDialogPriceIncrement);
        TextView tvPriceOption1 = dialogView.findViewById(R.id.tvPriceOption1);
        TextView tvPriceOption2 = dialogView.findViewById(R.id.tvPriceOption2);
        LinearLayout llOtherPriceContainer = dialogView.findViewById(R.id.llOtherPriceContainer);
        EditText etOtherPrice = dialogView.findViewById(R.id.etOtherPrice);

        // 从页面读取当前竞价、加价幅度（准备为 lambda 使用的“事实上 final”变量）
        int currentTmp = parseIntFromText(tvCurrentPrice != null ? tvCurrentPrice.getText().toString() : null);
        int incrementTmp = parseIntFromText(price_increment != null ? price_increment.getText().toString() : null);
        final int currentVal = currentTmp;
        final int incrementVal = incrementTmp;

        // 回填到弹窗：当前竞价、加价幅度
        if (tvDialogCurrentPrice != null) {
            tvDialogCurrentPrice.setText("当前竞价: ¥" + currentVal);
        }
        if (tvDialogPriceIncrement != null) {
            tvDialogPriceIncrement.setText("¥" + incrementVal);
        }

        // 计算两个推荐价格：current+increment, current+2*increment
        final int option1 = currentVal + Math.max(incrementVal, 0);
        final int option2 = currentVal + Math.max(incrementVal, 0) * 2;
        if (tvPriceOption1 != null) tvPriceOption1.setText("¥" + option1);
        if (tvPriceOption2 != null) tvPriceOption2.setText("¥" + option2);
        // 默认选中推荐价格1
        selectedBidPrice = option1;

        // 设置价格选择点击事件
        if (llPrice440 != null) {
            LinearLayout finalLlPrice448 = llPrice448;
            LinearLayout finalLlPriceOther = llPriceOther;
            llPrice440.setOnClickListener(v -> {
                selectPrice(llPrice440, finalLlPrice448, finalLlPriceOther);
                selectedBidPrice = option1;
                if (etOtherPrice != null) etOtherPrice.setText("");
                if (llOtherPriceContainer != null) llOtherPriceContainer.setVisibility(View.GONE);
                Toast.makeText(this, "选择价格：¥" + option1, Toast.LENGTH_SHORT).show();
            });
        }

        if (llPrice448 != null) {
            LinearLayout finalLlPrice440 = llPrice440;
            LinearLayout finalLlPriceOther1 = llPriceOther;
            llPrice448.setOnClickListener(v -> {
                selectPrice(llPrice448, finalLlPrice440, finalLlPriceOther1);
                selectedBidPrice = option2;
                if (etOtherPrice != null) etOtherPrice.setText("");
                if (llOtherPriceContainer != null) llOtherPriceContainer.setVisibility(View.GONE);
                Toast.makeText(this, "选择价格：¥" + option2, Toast.LENGTH_SHORT).show();
            });
        }

        if (llPriceOther != null) {
            LinearLayout finalLlPrice4401 = llPrice440;
            LinearLayout finalLlPrice4481 = llPrice448;
            llPriceOther.setOnClickListener(v -> {
                selectPrice(llPriceOther, finalLlPrice4401, finalLlPrice4481);
                if (llOtherPriceContainer != null) llOtherPriceContainer.setVisibility(View.VISIBLE);
                if (etOtherPrice != null) {
                    etOtherPrice.setText("");
                    etOtherPrice.requestFocus();
                }
            });
        }

        // 确保弹窗全屏宽度并显示圆角
        dialog.setOnShowListener(dialogInterface -> {
            BottomSheetDialog bottomSheetDialog = (BottomSheetDialog) dialogInterface;
            Window window = bottomSheetDialog.getWindow();
            if (window != null) {
                // 获取屏幕宽度
                android.util.DisplayMetrics metrics = new android.util.DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);
                int screenWidth = metrics.widthPixels;

                // 设置窗口背景为透明，让内容视图的背景显示出来
                window.setBackgroundDrawableResource(android.R.color.transparent);

                // 设置窗口属性
                WindowManager.LayoutParams params = window.getAttributes();
                params.width = screenWidth;
                params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                params.horizontalMargin = 0;
                params.verticalMargin = 0;
                window.setAttributes(params);

                // 移除所有padding和margin
                window.getDecorView().setPadding(0, 0, 0, 0);
                window.setLayout(screenWidth, ViewGroup.LayoutParams.WRAP_CONTENT);

                // 强制设置对话框视图的布局参数
                ViewGroup.LayoutParams dialogParams = dialogView.getLayoutParams();
                if (dialogParams != null) {
                    dialogParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    dialogView.setLayoutParams(dialogParams);
                }

                // 移除对话框视图的padding和margin
                dialogView.setPadding(0, 0, 0, 0);
                if (dialogView instanceof ViewGroup) {
                    ViewGroup viewGroup = (ViewGroup) dialogView;
                    ViewGroup.MarginLayoutParams marginParams =
                            (ViewGroup.MarginLayoutParams) viewGroup.getLayoutParams();
                    if (marginParams != null) {
                        marginParams.setMargins(0, 0, 0, 0);
                        viewGroup.setLayoutParams(marginParams);
                    }
                }

                // 确保背景圆角显示
                dialogView.setClipToOutline(true);

                // 查找并设置 BottomSheet 的背景
                View bottomSheet = bottomSheetDialog.findViewById(com.google.android.material.R.id.design_bottom_sheet);
                if (bottomSheet != null) {
                    bottomSheet.setBackgroundResource(android.R.color.transparent);
                }

                // 强制设置内容视图的背景
                dialogView.setBackgroundResource(R.drawable.bg_dialog);
            }
        });

        // 确定出价按钮
        Button btnConfirmBid = dialogView.findViewById(R.id.btnConfirmBid);
        if (btnConfirmBid != null) {
            btnConfirmBid.setOnClickListener(v -> {
                // 若选择了“其他价格”，读取输入并校验
                if (llOtherPriceContainer != null && llOtherPriceContainer.getVisibility() == View.VISIBLE && etOtherPrice != null) {
                    String input = etOtherPrice.getText() != null ? etOtherPrice.getText().toString().trim() : "";
                    if (!input.isEmpty()) {
                        try {
                            int custom = Integer.parseInt(input);
                            if (custom < currentVal) {
                                Toast.makeText(this, "自定义价格不能小于当前竞价", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            selectedBidPrice = custom;
                        } catch (NumberFormatException e) {
                            Toast.makeText(this, "请输入合法的数字价格", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } else {
                        Toast.makeText(this, "请输入自定义价格", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                // 登录检查
                Long uid = com.example.petshopping.utils.TokenManager.getUserId(this);
                if (uid == null || uid <= 0) {
                    Toast.makeText(this, "请先登录后再出价", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(this, com.example.petshopping.ui.login.PhoneLoginActivity.class);
                    startActivity(intent);
                    return;
                }

                // 组装创建出价请求体
                com.example.petshopping.model.AppPetAuctionBidSaveReqVO reqVO = new com.example.petshopping.model.AppPetAuctionBidSaveReqVO();
                // 拍卖商品ID
                String itemIdStr = getIntent().getStringExtra("id");
                Long itemId = null;
                try { itemId = itemIdStr != null ? Long.parseLong(itemIdStr) : null; } catch (Exception ignored) {}
                reqVO.setAuctionItemId(itemId);
                // 出价用户ID、昵称、头像
                reqVO.setBidderId(uid);
                reqVO.setBidderName(com.example.petshopping.utils.UserInfoManager.getUserNickname(this));
                reqVO.setBidderAvatar(com.example.petshopping.utils.UserInfoManager.getUserAvatar(this));
                // 出价金额（单位：与后端一致，若后端是元，直接填写；若是分，请在此乘以100）
                reqVO.setBidPrice(selectedBidPrice);
                // 出价状态（状态：1-有效）15
                reqVO.setStatus(1);

                // 发送创建出价请求
                retrofit2.Call<com.example.petshopping.model.CommonResult<com.example.petshopping.model.AppPetAuctionBidRespVO>> call =
                        com.example.petshopping.network.RetrofitClient.getInstance().getApiService().createPetAuctionBid(reqVO);
                call.enqueue(new retrofit2.Callback<com.example.petshopping.model.CommonResult<com.example.petshopping.model.AppPetAuctionBidRespVO>>() {
                    @Override
                    public void onResponse(retrofit2.Call<com.example.petshopping.model.CommonResult<com.example.petshopping.model.AppPetAuctionBidRespVO>> call,
                                           retrofit2.Response<com.example.petshopping.model.CommonResult<com.example.petshopping.model.AppPetAuctionBidRespVO>> response) {
                        if (!response.isSuccessful() || response.body() == null) {
                            Toast.makeText(AquariumDetailActivity.this, "出价失败：网络或服务器错误", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        com.example.petshopping.model.CommonResult<com.example.petshopping.model.AppPetAuctionBidRespVO> result = response.body();
                        if (!result.isSuccess()) {
                            String msg = result.getMsg() != null ? result.getMsg() : "出价失败";
                            Toast.makeText(AquariumDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                            return;
                        }

                        // 成功：关闭弹窗，刷新价格、刷新出价列表与商品详情
                        Toast.makeText(AquariumDetailActivity.this, "出价成功！价格：¥" + selectedBidPrice, Toast.LENGTH_SHORT).show();
                        dialog.dismiss();

                        // 刷新拍卖商品、出价列表
                        initProductDataFromServer(itemIdStr, tvProductTitle != null ? tvProductTitle.getText().toString() : null);
                        initBidRecordsFromServer(itemIdStr);
                    }

                    @Override
                    public void onFailure(retrofit2.Call<com.example.petshopping.model.CommonResult<com.example.petshopping.model.AppPetAuctionBidRespVO>> call, Throwable t) {
                        Toast.makeText(AquariumDetailActivity.this, "出价失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            });
        }

        dialog.show();
    }

    // 处理价格选择
    private void selectPrice(LinearLayout selectedLayout, LinearLayout... otherLayouts) {
        // 设置选中的布局背景和文字颜色
        selectedLayout.setBackgroundResource(R.drawable.bg_price_selected);
        updatePriceTextColor(selectedLayout, android.graphics.Color.parseColor("#E32517")); // 红色

        // 设置其他布局为未选中背景和文字颜色
        for (LinearLayout layout : otherLayouts) {
            if (layout != null) {
                layout.setBackgroundResource(R.drawable.bg_price_normal);
                updatePriceTextColor(layout, android.graphics.Color.parseColor("#666666")); // 灰色
            }
        }
    }

    // 更新价格文字颜色
    private void updatePriceTextColor(LinearLayout priceLayout, int color) {
        if (priceLayout != null) {
            // 查找 LinearLayout 中的 TextView 并更新颜色
            for (int i = 0; i < priceLayout.getChildCount(); i++) {
                View child = priceLayout.getChildAt(i);
                if (child instanceof TextView) {
                    ((TextView) child).setTextColor(color);
                }
            }
        }
    }

    // 解析整数字符串，容错去除货币符号和空格
    private int parseIntFromText(String text) {
        if (text == null) return 0;
        try {
            // 去掉前缀“¥ ”等非数字字符
            String cleaned = text.replaceAll("[^0-9]", "");
            if (cleaned.isEmpty()) return 0;
            return Integer.parseInt(cleaned);
        } catch (Exception ignored) {
            return 0;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清理定时器
        if (countdownHandler != null && countdownRunnable != null) {
            countdownHandler.removeCallbacks(countdownRunnable);
        }
        if (carouselHandler != null && carouselRunnable != null) {
            carouselHandler.removeCallbacks(carouselRunnable);
        }
    }
}